package com.example.config.udpsocket;

import com.example.service.TEquipmentService;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.*;

@Slf4j
@Data
@Component
@NoArgsConstructor
public class UDPSocketServer implements Runnable{

    @Value("${UDPSocketPort}")
    private Integer UDPSocketPort;

    private UDPSocketServer udpSocketServer;

    public void setPort(Integer port){
        this.UDPSocketPort = port;
    }
    public static void main(String[] args) throws IOException {
        new UDPSocketServer().start(2325);
    }

    public void start() throws IOException {
        start(null);
    }

    public void start(Integer port) throws IOException {
        udpSocketServer = new UDPSocketServer();
        udpSocketServer.setPort(UDPSocketPort);
        Thread t = new Thread(udpSocketServer);
        t.start();
//        udpSocketServer.run();
    }

    @SneakyThrows
    @Override
    public void run() {
        DatagramSocket socket = new DatagramSocket(UDPSocketPort);
        DatagramPacket packet = null;
        byte[] data = null;
        log.info("UDPSocketServer启动，端口："+UDPSocketPort);
        while(true){
            data = new byte[1024];//创建字节数组，指定接收的数据包的大小
            packet = new DatagramPacket(data, data.length);
            socket.receive(packet);//此方法在接收到数据报之前会一直阻塞
            String info = new String(packet.getData(), 0, packet.getLength());
//            Thread thread = new Thread(new UDPClientSocket(socket, packet));
//            thread.start();
            InetAddress address = packet.getAddress();
//            log.info("当前客户端的IP为："+address.getHostAddress());
            UDPClientSocket udpClientSocket = new UDPClientSocket(socket, packet);
            udpClientSocket.run();
        }
    }
}
